const Modal = require("../modal/topic")

class Topic {
  constructor() {
    this.instance = null
  }
  static get Instance() {
    return this.instance || (this.instance = new Topic())
  }
  async getTopics(itemNum, skipNum, q) {
    const topics = await Modal
      .find({ name: new RegExp(decodeURIComponent(q)) })
      .limit(itemNum)
      .skip(skipNum)
    return topics
  }

  async getTopicById(topicId, fields = "") {
    const querySelector =
      fields &&
      fields
        .split(";")
        .filter(v => v)
        .map(v => " +" + v)
        .join("")
    const topic = await Modal.findById(topicId)
      .select(querySelector)
      .exec()
    return topic
  }

  async addTopic(data) {
    const topic = new Modal(data)
    await topic.save()
    return topic
  }

  async delTopicById(topicId) {
    const topic = await Modal.findByIdAndRemove(topicId)
    return topic
  }

  async updateTopic(topicId, data) {
    const topic = await Modal.findByIdAndUpdate(topicId, data)
    return topic
  }
}

const I = Topic.Instance

module.exports = I
